import { useReducer } from "react"

// reducer
const reduce = (state, action) => {
  const { type, payload } = action
  switch (type) {
    case 'addAge':
      return { ...state, age: state.age + payload }
    case 'changePerson':
      return { ...state, ...payload }
    default:
      return state
  }
}

// 初始值
const inialPerson = {
  name: '夏天',
  age: 18,
  gender: '男'
}

export default function ReducerDemo() {

  const [state, dispatch] = useReducer(reduce, inialPerson)
  const { name, age, gender } = state
  const newPerson = { name: '周一帆', age: 17, gender: '女' }
  return (
    <>
      <h2>useReducer的使用</h2>
      <ul>
        <li>姓名: {name}</li>
        <li>年龄:{age}</li>
        <li>性别:{gender}</li>
      </ul>
      <button onClick={() => dispatch({ type: 'addAge', payload: 1 })}>添加年龄</button>
      <button onClick={() => dispatch({ type: 'addAge', payload: -1 })}>减小年龄</button>
      <button onClick={() => dispatch({ type: 'changePerson', payload: newPerson })}>换人</button>
    </>
  )
}